import * as Cesium from 'cesium'

const prefix = import.meta.env.VITE_BASE_URL
//高度测量类
export default class MeasureHeight {
  constructor(viewer) {
    this.viewer = viewer
    this.initEvents()
    this.positions = []
    this.vertexEntities = new Cesium.EntityCollection()
    this.labelEntity = undefined
    this.lineEntity = undefined
    this.isMeasure = false
    this.measureHeight = 0 //测量结果
  }

  //初始化事件
  initEvents() {
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
    this.MeasureStartEvent = new Cesium.Event() //开始事件
    this.MeasureEndEvent = new Cesium.Event() //结束事件
    // 移除默认双击事件trackedEntity
    this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
  }

  //激活
  activate() {
    this.deactivate()
    this.registerEvents() //注册鼠标事件  
    this.isMeasure = true
    this.measureHeight = 0
    this.positions = []
  }

  //禁用
  deactivate() {
    if (!this.isMeasure) return
    this.unRegisterEvents()
    this.isMeasure = false
  }

  //清空绘制
  clear() {
    //清除线对象
    this.viewer.entities.remove(this.lineEntity)
    this.lineEntity = undefined

    //清除文本
    this.viewer.entities.remove(this.labelEntity)
    this.labelEntity = undefined

    //清除节点
    this.vertexEntities.values.forEach(item => {
      this.viewer.entities.remove(item)
    })
    this.vertexEntities.removeAll()
  }

  // Cartesian3转point3d格式
  cartesian3ToPoint3D(position) {
    const cartographic = Cesium.Cartographic.fromCartesian(position)
    const lon = Cesium.Math.toDegrees(cartographic.longitude)
    const lat = Cesium.Math.toDegrees(cartographic.latitude)
    return { x: lon, y: lat, z: cartographic.height }
  }

  //创建线对象
  createLineEntity() {
    this.lineEntity = this.viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(e => {
          return this.positions
        }, false),
        width: 2,
        material: Cesium.Color.YELLOW,
        // depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
        //   color: Cesium.Color.RED,
        // }),
      }
    })
  }

  //创建结果文本标签
  createLabel() {
    this.labelEntity = this.viewer.entities.add({
      position: new Cesium.CallbackProperty(e => {
        return this.positions[this.positions.length - 1] //返回最后一个点
      }, false),
      label: {
        text: "",
        scale: 0.5,
        font: 'normal 40px MicroSoft YaHei',
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        pixelOffset: new Cesium.Cartesian2(0, -30),
        outlineWidth: 9,
        outlineColor: Cesium.Color.WHITE
      }
    })
  }

  //创建线节点
  createVertex(index) {
    let vertexEntity = this.viewer.entities.add({
      position: new Cesium.CallbackProperty(e => {
        return this.positions[index]
      }, false),
      type: "MeasureHeightVertex",
      point: {
        color: Cesium.Color.FUCHSIA,
        pixelSize: 6,
        // disableDepthTestDistance: 2000,
      },
    })
    this.vertexEntities.add(vertexEntity)
  }

  //注册鼠标事件
  registerEvents() {
    this.leftClickEvent()
    this.doubleClickEvent()
    this.mouseMoveEvent()
  }

  //左键点击事件
  leftClickEvent() {
    //单击鼠标左键画点点击事件
    this.handler.setInputAction(e => {
      let position = this.viewer.scene.camera.pickEllipsoid(e.position, this.viewer.scene.globe.ellipsoid)
      if (!position) {
        position = this.viewer.scene.pickPosition(e.position)
      }
      if (!position) return
      if (this.positions.length == 0) { //首次点击
        this.positions.push(position)
        this.createVertex(0)
        this.createLineEntity()
        this.createLabel()
      } else { //第二次点击结束测量
        this.measureEnd()
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
  }

  //鼠标移动事件
  mouseMoveEvent() {
    this.handler.setInputAction(e => {
      if (!this.isMeasure) return
      let position = this.viewer.scene.camera.pickEllipsoid(e.endPosition, this.viewer.scene.globe.ellipsoid)
      if (!position) {
        position = this.viewer.scene.pickPosition(e.startPosition)
      }
      if (!position) return
      this.handleMoveEvent(position)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  }

  //处理鼠标移动
  handleMoveEvent(position) {
    if (this.positions.length < 1) return
    let firstPoint = this.cartesian3ToPoint3D(this.positions[0]) //第一个点
    let movePoint = this.cartesian3ToPoint3D(position) //鼠标移动点
    // 计算两点之间的高度
    const h = this.viewer.scene.globe.getHeight(Cesium.Cartographic.fromCartesian(position)) - this.viewer.scene.globe.getHeight(Cesium.Cartographic.fromCartesian(this.positions[0]))
    const twoPosition = Cesium.Cartesian3.fromDegrees(movePoint.x, movePoint.y, movePoint.z)
    if (this.positions.length < 2) {
      this.positions.push(twoPosition)
      this.createVertex(1)
    } else {
      this.positions[1] = twoPosition
      this.measureHeight = h.toFixed(3)
      this.labelEntity.label.text = "高度：" + this.measureHeight + " 米"
    }
  }

  //右键事件
  doubleClickEvent() {
    this.handler.setInputAction(e => {
      if (this.isMeasure) {
        this.deactivate()
        this.clear()
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
  }

  //测量结束
  measureEnd() {
    this.deactivate()
    this.MeasureEndEvent.raiseEvent(this.measureHeight) //触发结束事件 传入结果
  }

  //解除鼠标事件
  unRegisterEvents() {
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  }
}